package com.yt.website.action;

import com.yt.core.MsgBean;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.util.MD5Util;
import com.yt.website.action.base.BaseAction;
import com.yt.website.api.interfaces.UserInfoService;
import com.yt.website.api.model.UserInfo;
import com.yt.website.exception.DataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/")
public class LoginAction extends BaseAction{

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/toLogin")
    public ModelAndView toLogin() {
        ModelAndView mav = new ModelAndView("login");
        return mav;
    }

    @RequestMapping("/login")
    public
    @ResponseBody
    Object login(@RequestParam(value="mobile", required = true) String mobile,
                 @RequestParam(value="password", required = true) String password,
                 @RequestParam(value="code", required = true) String code,
                 HttpServletRequest request) throws Exception{
        if(!CodeAction.checkCode(code, request)){
            throw new DataException("验证码错误");
        }
        QueryFilter filter = new DynamicSQLFilterImpl();
        filter.addFilter("Q_mobile_S_EQ", mobile);

        List<UserInfo> userList = userInfoService.find(filter);
        if(userList != null && !userList.isEmpty()){

            UserInfo userInfo = userList.get(0);
            if(userInfo.getPassword().equals(MD5Util.MD5(password))){
                setLoginUser(request, userInfo);
                MsgBean msg = new MsgBean();
                return msg.returnMsg();
            }
        }

        throw new DataException("手机号或密码错误！");
    }
}
